package com.vpen.account.demo.core;

import com.vpen.account.demo.model.dto.AccountUserDetails;
import com.vpen.account.demo.model.dto.LoginDto;
import com.vpen.account.demo.model.enums.LoginType;
import com.vpen.account.demo.utils.LoginUserUtils;
import com.vpen.account.demo.utils.RsaUtils;
import com.vpen.account.demo.utils.SpringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 自定义登录密码校验
 *
 * @author 韦鹏
 * @date 2022/8/15 17:19
 */

@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class LoginAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //获取输入的用户名
        String username = authentication.getName();
        //获取密码
        String credentials = (String) authentication.getCredentials();

        String password = null;
        LoginType loginType = LoginType.getType();
        if (LoginType.USERNAME.equals(loginType)) {
            // 解密传输过来的明文
            password = RsaUtils.decryptStr(credentials);
        }
        AccountUserDetails user = (AccountUserDetails) LoginUserUtils.getAccountLoginService(loginType)
                .getUserByCondition(new LoginDto(username, password, SpringUtils.getParameter("phone"), SpringUtils.getParameter("code")));
        return new UsernamePasswordAuthenticationToken(user, user.getPassword(), user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }
}
